package servlets;

import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.User;

import database.DBHandler;

public class Entry extends AServlet {
	private static final long serialVersionUID = -402035819244873989L;
	private final String magic = "magic";
	
	public void doGet(HttpServletRequest request,HttpServletResponse response)
    	throws ServletException, IOException {
		if (request.getParameter("Logout") != null){
			request.getSession().invalidate();
			response.sendRedirect(request.getContextPath() + "/index.jsp");
			return;
		}
		return;
	}
	
	private void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException{
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		if (userName.equals("") || password.equals("")){
			forwardOnError(request, response, "LoginError", "Error: Please input all fields.", "/index.jsp");
			return;
		}
		
		DBHandler dbh = DBHandler.getHandler();
		Connection con = dbh.getLocalCon();
		User result;
		try {
			result = dbh.getUser(userName,con);
		} catch (Exception e) {
			finishTransaction(con, false);
			e.printStackTrace();
			throw new ServletException();
		}
		if (result.getPassword().equals(password)){
			request.getSession(true).setAttribute("LoginStatus", true);
			request.getSession(true).setAttribute("LoginName", userName);
			if(result.isAdmin())
				request.getSession(true).setAttribute("isAdmin", true);
			else
				request.getSession(true).setAttribute("isAdmin", false);
			finishTransaction(con, true);
			dbh.returnLocalCon(con);
			try {
				response.sendRedirect(request.getContextPath() + "/Home");
			} catch (Exception e) {
				finishTransaction(con, false);
				e.printStackTrace();
				throw new ServletException();
			}
			return;
		}
		else{
			finishTransaction(con, false);
			dbh.returnLocalCon(con);
			forwardOnError(request, response, "LoginError", "The password and username did not match.", "/index.jsp");
			return;
		}		
	}

	public void doPost(HttpServletRequest request,HttpServletResponse response)
		throws ServletException, IOException{
		if (request.getParameter("Register") != null)
			doRegister(request, response);
		else if (request.getParameter("Login") != null)
			doLogin(request, response);
		else 
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
	}
	
	public void doRegister(HttpServletRequest request,HttpServletResponse response) throws ServletException{
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		String name = request.getParameter("name");
		String family = request.getParameter("family");
		String phone = request.getParameter("phone");
		String magicString = request.getParameter("magicString");
		
		if (userName.equals("") || password.equals("") || name.equals("") || family.equals("") || 
				phone.equals("")){
			forwardOnError(request, response, "RegistrationError", "Error: Please input all fields.", "/index.jsp");
			return;
		}
		
		try{
			Long.parseLong(phone);
			if(phone.length()<7) throw new NumberFormatException();
		}
		catch(NumberFormatException e){
			forwardOnError(request, response, "RegistrationError", "Error: Please input a legal phone number", "/index.jsp");
			return;
		}
		DBHandler dbh = DBHandler.getHandler();
		Connection con = dbh.getLocalCon();
		boolean result = false;
		try {
			if (!magicString.equals("")){
				if (magicString.equals(magic))
					result = dbh.addUser(new User(userName, password, name, family, phone, true, new ArrayList<String>()), con);
				else{
					finishTransaction(con, false);
					dbh.returnLocalCon(con);
					request.getSession(true).setAttribute("RegistrationError", "Wrong magic string!");
					RequestDispatcher rd = getServletConfig().getServletContext().getRequestDispatcher("/index.jsp");
					rd.forward(request, response);
					return;
				}
			}
			else
				result = dbh.addUser(new User(userName, password, name, family, phone, false, new ArrayList<String>()), con);
		} catch (Exception e) {
			finishTransaction(con, false);
			dbh.returnLocalCon(con);
			forwardOnError(request, response, "RegistrationError", "Error: User already exists!", "/index.jsp");
			return;
		}
		
		if (!result){
			try {
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			} catch (IOException e) {
				finishTransaction(con, false);
				e.printStackTrace();
				throw new ServletException();
			}
		}
		
		finishTransaction(con, true);
		dbh.returnLocalCon(con);
		request.getSession(true).setAttribute("LoginStatus", true);
		request.getSession(true).setAttribute("LoginName", userName);
		request.getSession(true).setAttribute("isAdmin", magicString.equals(magic));
		try {
			response.sendRedirect(request.getContextPath() + "/Home");
		} catch (IOException e) {
			finishTransaction(con, false);
			e.printStackTrace();
			throw new ServletException();
		}
		return;
	}
}